package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class PathClassLoader extends ClassLoader {
    private File dir;

    public PathClassLoader(String path) {
        dir = new File(path);
//        System.out.println(dir);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if(dir != null) {
            File clazzFile = new File(dir, name + ".class");
            if(clazzFile.exists()) {
                FileInputStream input = null;
                try {
                    input = new FileInputStream(clazzFile);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while((len = input.read(buffer)) != -1) {
                        baos.write(buffer, 0, len);
                    }
//                    System.out.println("name: "+name);
                    String namee = name.replace("/",".");
                    return defineClass(namee, baos.toByteArray(), 0, baos.size());
                } catch(Exception e) {
                    throw new ClassNotFoundException(name, e);
                } finally {
                    if(input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return super.findClass(name);
    }


    public static void main(String[] args) throws Exception{

        PathClassLoader pathClassLoader = new PathClassLoader("D:/webapps/web_demo_war_exploded/WEB-INF/classes");

        Class clazz = pathClassLoader.findClass("com/lagou/edu/servlet/TestServlet");


        //利用Java反射机制创建实例测试方法
        HttpServlet httpServlet = (HttpServlet)clazz.newInstance();
        httpServlet.doGet(null,null);

        /* File file = new File("D:\\webapps\\web_demo_war_exploded\\WEB-INF\\classes\\com\\lagou\\edu\\servlet\\TestServlet.class");

        System.out.println(file.exists());*/

    }
}
